package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.cmn.client.DictFeignClient;
import com.atguigu.yygh.common.handler.YyghException;
import com.atguigu.yygh.enums.DictEnum;
import com.atguigu.yygh.hosp.repository.HospitalRepository;
import com.atguigu.yygh.hosp.service.HospitalService;
import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.vo.hosp.HospitalQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HospitalServiceImpl implements HospitalService {
    @Autowired
    private HospitalRepository hospitalRepository;

    @Autowired
    private DictFeignClient dictFeignClient;

    //上传医院
    @Override
    public void save(Map<String, Object> paramMap) {
        //1 paramMap转化成实体
        String paramJson = JSONObject.toJSONString(paramMap);
        Hospital hospital = JSONObject.parseObject(paramJson, Hospital.class);
        //2 根据hoscode到mongo查询医院信息
        Hospital targetHospital = hospitalRepository
                .getHospitalByHoscode(hospital.getHoscode());
        if(targetHospital!=null){
            //3 如果有，更新数据
            hospital.setId(targetHospital.getId());
            hospital.setCreateTime(targetHospital.getCreateTime());
            hospital.setStatus(targetHospital.getStatus());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            hospitalRepository.save(hospital);
        }else{
            //4 如果没有，插入数据
            //0：未上线 1：已上线
            hospital.setStatus(0);
            hospital.setCreateTime(new Date());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            hospitalRepository.save(hospital);
        }

    }

    //获取医院信息
    @Override
    public Hospital getByHoscode(String hoscode) {
        Hospital hospital = hospitalRepository.getHospitalByHoscode(hoscode);
        return hospital;
    }

    //获取分页列表
    @Override
    public Page<Hospital> selectPage(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {
        //1、创建分页对象
        //1.1创建排序对象
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        //1.2分页查询对象，0是第一页
        Pageable pageable = PageRequest.of(page-1,limit,sort);
        //2、创建筛选条件模板
        //2.1创建查询条件对象
        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo,hospital);
        hospital.setIsDeleted(0);
        //2.2创建筛选条件构造器
        ExampleMatcher matcher = ExampleMatcher.matching()//构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写
        Example<Hospital> example = Example.of(hospital,matcher);
        //3、调用方法查询分页结果
        Page<Hospital> hospitalPage = hospitalRepository.findAll(example, pageable);

        //4、跨模块调cmn模块实现编码翻译
        hospitalPage.getContent().stream().forEach(item->{
            this.packHospital(item);
        });

        return hospitalPage;
    }

    //更新上线状态
    @Override
    public void updateStatus(String id, Integer status) {
        if(status.intValue() == 0 || status.intValue() == 1) {
            //根据id查询医院信息
            Hospital hospital = hospitalRepository.findById(id).get();
            hospital.setStatus(status);
            hospital.setUpdateTime(new Date());
            hospitalRepository.save(hospital);
        }
    }

    //获取医院详情
    @Override
    public Map<String, Object> show(String id) {
        //根据id查询医院信息
        Hospital hospital =
               this.packHospital( hospitalRepository.findById(id).get());
        Map<String, Object> result = new HashMap<>();
        //医院基本信息（包含医院等级）
        result.put("hospital",hospital);
        //单独处理更直观
        result.put("bookingRule", hospital.getBookingRule());
        //不需要重复返回
        hospital.setBookingRule(null);
        return result;
    }

    //获取医院名称
    @Override
    public String getHospName(String hoscode) {
        Hospital hospital = this.getByHoscode(hoscode);
        if(hospital==null){
            throw  new YyghException(20001,"医院信息有误");
        }
        return hospital.getHosname();
    }

    //根据医院名称获取医院列表
    @Override
    public List<Hospital> findByHosname(String hosname) {
        List<Hospital> list =
                hospitalRepository.getHospitalByHosnameLike(hosname);
        return list;
    }

    //医院预约挂号详情
    @Override
    public Map<String, Object> getHospByHoscode(String hoscode) {
        Map<String, Object> result = new HashMap<>();
        Hospital hospital = this.packHospital(hospitalRepository.getHospitalByHoscode(hoscode));
        result.put("hospital", hospital);
        //预约规则
        result.put("bookingRule", hospital.getBookingRule());
        //不需要重复返回
        hospital.setBookingRule(null);
        return result;
    }

    //跨模块调cmn模块实现编码翻译
    private Hospital packHospital(Hospital hospital) {
        //医院等级
        String hostypeString = dictFeignClient.getName(
                DictEnum.HOSTYPE.getDictCode(), hospital.getHostype());
        String provinceString = dictFeignClient.getName(hospital.getProvinceCode());
        String cityString = dictFeignClient.getName(hospital.getCityCode());
        String districtString = dictFeignClient.getName(hospital.getDistrictCode());
        hospital.getParam().put("hostypeString", hostypeString);
        hospital.getParam().put("fullAddress", provinceString + cityString + districtString + hospital.getAddress());
        return hospital;
    }
}
